package com.wei.myhame.utils;

import android.content.Context;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by gzl on 2019/11/5 9:02
 * title：
 */
public class Utils {

    private static final double EARTH_RADIUS = 6378137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 根据两点间经纬度坐标（double值），计算两点间距离，
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return 距离：单位为米
     */
    public static double DistanceOfTwoPoints(double lat1,double lng1,
                                             double lat2,double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return Math.round (s / 100d) / 10d;
    }


    public static RequestBody toRequestBody(Map<String,Object> map){
        Gson gson = new Gson();
        String s = gson.toJson(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), s);
        return requestBody;
    }

    /**
     *
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale +0.5f);
    }


    /**
     * <li>jsonitem
     */
    public static String getjsonitem(String Json, String item) {
        try {
            JSONObject jsonObject = new JSONObject(Json);
            return jsonObject.optString(item);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return Json;
    }

}
